#!/usr/bin/env python

import os, sys
import time
import struct

# Logs chats into HTML format
# Also can log to gallery

class Logger:

   def __init__(self,blend):
      self.blend = blend;

   def start(self,conv):
      jid = conv.buddy.jid.replace("/","_");
      fDir = os.path.join('logs',str(self.blend.currentAccount.username),str(jid));

      # Create the directories if they don't exist
      if self.blend.config.log:
         if os.path.exists(fDir) == False:
            if os.path.exists(os.path.join('logs',str(self.blend.currentAccount.username))):
               os.mkdir(fDir);
            else:
               os.mkdir(os.path.join('logs',str(self.blend.currentAccount.username)));
               os.mkdir(fDir);
      
         # Create the file
         ti = time.strftime('%Y-%m-%d.%H%M%S',time.localtime());
      
         fName = "%s.html" % ti;
      
         conv.logRes = open(os.path.join(fDir,fName),'w');
      conv.galleryMsgs = [];

   def sendToGallery(self,conv):
      msgs = conv.galleryMsgs;
      gallery = self.blend.conn.roster.get_buddy('gallery@m');
      body = "";
      for i in range(0,len(msgs)):
         msg = msgs[i];

         if type(msg[1]) == type(float(1)):
            ts = long(msg[1]);
         else:
            ts = long(time.mktime(msg[1].timetuple())); 
         #ts = long(msg[1]);

         fa = str(msg[0]);
         faL = len(fa);
         
         ta = str(msg[2]);
         taL = len(ta);
          
         by = str(msg[3])
         byL = len(by);
         
         fg = int(msg[4]);
         
         bundle = struct.pack('>QH%dsH%dsH%dsi' % (faL,taL,byL),ts,faL,fa,taL,ta,byL,by,fg);
         ln = struct.pack('>i',len(bundle));

         body += ln + bundle;

      t = time.localtime();
      formatted = "%s-%s-%s" % (t.tm_year,t.tm_mon,t.tm_mday);
      na = conv.buddy.name + "-" + formatted + ".mxm";         
      self.blend.conn.gallery_message(gallery,body,len(msgs),na);

   # Gallery
   def glog(self,conv,message):
      fromAlias = self.blend.currentAccount.name;
      curTime = message.time;
      toAlias = message.buddy.name;
      flags = message.get_flags;
      msg = message.message;
      
      # Store for later
      conv.galleryMsgs.append((fromAlias,curTime,toAlias,msg,flags));

   def log(self,conv,data):
      try:
         # File
         if self.blend.config.log == True:
            conv.logRes.write(data);
            conv.logRes.flush();
      except:
         pass;
         
   def endLog(self,conv):
      try:
         conv.logRes.close();
      except:
         pass;
         